import React, { useState, useEffect, useRef, useContext } from 'react';
import PropType from 'prop-types';
import { Button, Form, Input, InputNumber, Popconfirm, Select, Space, Table } from 'antd';

import styles from './index.css';

const EditableContext = React.createContext<any>();


interface TableItem {
    id: string,
    hisId: String,
    name: string,
    professional_id: string
    professional_name: string
}


// interface EditableRowProps {
//     index: number;
// }

// const EditableRow: React.FC<EditableRowProps> = ({ index, ...props }) => {
//     const [form] = Form.useForm();
//     return (
//         <Form form={form} component={false}>
//             <EditableContext.Provider value={form}>
//                 <tr {...props} />
//             </EditableContext.Provider>
//         </Form>
//     );
// };

interface EditableCellProps extends React.HTMLAttributes<HTMLElement> {
    editing: boolean;
    dataIndex: string;
    title: any;
    inputType: 'number' | 'text';
    record: TableItem;
    index: number;
    children: React.ReactNode;
}

const EditableCell: React.FC<EditableCellProps> = ({
    editing,
    dataIndex,
    title,
    inputType,
    record,
    index,
    children,
    ...restProps
}) => {
    // const inputNode = inputType === 'number' ? <InputNumber /> : <Input />;

    let inputNode;

    switch (dataIndex) {
        case "name":
            inputNode = <Input />;
            break;
        case "professional_id":

            let tmpOptions = [];

            tmpOptions.push({
                label: "人民医院",
                value: "001"
            });

            tmpOptions.push({
                label: "中医医院",
                value: "002"
            })

            inputNode = <Select options={tmpOptions} onSelect={(value) => {
                let name = tmpOptions.find(item => item.value === value).label;

                record.professional_name = name;

            }} >
                {/* <Select.Option value={
                    {
                        key: "人民医院",
                        value: "001"
                    }
                }>人民医院</Select.Option>
                <Select.Option value={
                    {
                        key: "中医医院",
                        value: "002"
                    }
                }>中医医院</Select.Option> */}
            </Select >
            break;
        default:
            inputNode = <Input />;
    }

    return (
        <td {...restProps}>
            {editing ? (
                <Form.Item
                    name={dataIndex}
                    style={{ margin: 0 }}
                    rules={[
                        {
                            required: true,
                            message: `Please Input ${title}!`,
                        },
                    ]}
                >
                    {inputNode}
                </Form.Item>
            ) : (
                    children
                )}
        </td>
    );
};

const tableDatas: TableItem[] = [];

for (let i: number = 0; i < 30; i++) {

    let tableData: TableItem = {
        id: `id${i}`,
        hisId: `hisId${i}`,
        name: `name${i}`,
        professional_id: `professional_id${i}`,
        professional_name: `professional_name${i}`,
    }
    tableDatas.push(tableData);
}

const DoctorTable = (props: any) => {
    const [form] = Form.useForm();
    const [tableData, setTableData] = useState<TableItem[]>([]);
    const [editingKey, setEditingKey] = useState<string>('')

    const [page, setPage] = useState<number>(1);
    const pageSize = 15;

    const isEditing = (record: TableItem) => record.id === editingKey;

    const columns = [
        {
            title: '行号',
            width: '40px',
            render: (text, record: TableItem, index) => {
                let rowNum = page * pageSize - pageSize + index + 1;
                return (<div>{rowNum}</div>)
            }
        },

        {
            title: 'HIS_ID',
            dataIndex: 'hisId',
            width: '40px',
            editable: true,
        },
        {
            title: '医生姓名',
            dataIndex: 'name',
            width: '40px',
            editable: true,
        },
        {
            title: '所属专业',
            dataIndex: 'professional_id',
            width: '40px',
            editable: true,
            render: (text, record: TableItem, index) => {
                return (<span>{record.professional_name}</span>)
            }
        },
        {
            title: '操作',
            width: '80px',
            render: (text, record: TableItem, index) => {
                const editable = isEditing(record);
                return editable ? (
                    <span>
                        <a onClick={() => {
                            saveRecode(record);
                        }} style={{ marginRight: 8 }}>
                            Save
                        </a>
                        <Popconfirm title="Sure to cancel?" onConfirm={() => {
                            setEditingKey('');
                        }}>
                            <a>Cancel</a>
                        </Popconfirm>
                    </span>
                ) : (
                        <a disabled={editingKey !== ''} onClick={() => {
                            form.setFieldsValue({ ...record });
                            setEditingKey(record.id)
                        }}>
                            Edit
                        </a>
                    );
            }
        },

        {
            title: 'ID',
            dataIndex: 'id',
            width: '0.01px',
            className: styles.HideTableCol,
            editable: true,
        },

    ]

    const mergedColumns = columns.map(col => {
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            onCell: (record: TableItem) => ({
                record,
                // inputType: col.dataIndex === 'age' ? 'number' : 'text',
                inputType: 'text',
                dataIndex: col.dataIndex,
                title: col.title,
                editing: isEditing(record),
            }),
        };
    });


    const saveRecode = async (record: TableItem) => {

        const values = (await form.validateFields()) as TableItem;

        let tmpData = [...tableData];

        // let tmpData = tableDatas; 
        let index = tmpData.findIndex(item => item.id === values.id);

        if (index > -1) {

            let tmpItem = tmpData[index];

            tmpItem.name = values.name;
            tmpItem.professional_id = values.professional_id;
            // tmpItem.professional_name

            tmpData.splice(index, 1, tmpItem);
        }
        else {

            tmpData.push(values);
        }

        setTableData(tmpData);
        setEditingKey('');

        console.log(values);

    }


    useEffect(() => {
        setTableData(tableDatas);

        return () => { }
    }, [])

    useEffect(() => {

        console.log(props.height);

    }, [props.height])


    const add = () => {

        form.resetFields();
        let tmpdata = [...tableData];

        let item: TableItem = {
            name: "",
            id: "1111",
            hisId: "123456",
            professional_id: "",
            professional_name: ""
        }

        tmpdata.unshift(item);
        setTableData(tmpdata);
        setEditingKey(item.id);

    }


    return (
        <div>
            <Button onClick={() => add()} > 点一下</Button>
            <Form form={form} component={false}>
                <Table
                    // scroll={{ y: '400px' }}
                    pagination={{
                        current: page,
                        pageSize: pageSize,
                        onChange: (page, pageSize) => {
                            setPage(page);
                        },
                        showTotal: function showTotal(total) {
                            return `总共 ${total} 条`;
                        }
                    }}
                    rowKey={(recode) => recode.id} bordered columns={mergedColumns} dataSource={tableData} components={{
                        body: {
                            cell: EditableCell,
                        },
                    }} ></Table>
            </Form>
        </div>)
}

DoctorTable.prototype = {
    height: PropType.number,
    onTestButtonClick: PropType.func
}


const DoctorPage = (props: any) => {

    const [height, setHeight] = useState<number>(800);


    useEffect(() => {

        console.log("mount");

        return () => {
            console.log("unmount");
        }
    }, [])

    useEffect(() => {

        console.log("useEffect")
    });



    return (
        <div>

            <DoctorTable height={height}   ></DoctorTable>
        </div >
    )

}



export default DoctorPage;
